//
//  UserAccount.swift
//  SinaWeibo
//
//  Created by celeste on 16/5/18.
//  Copyright © 2016年 celeste. All rights reserved.
//

import UIKit

private let LDWeiboUserAccountKey = "ld.userAccount"

class UserAccount: NSObject {
    
    static let sharedUserAccount = UserAccount()
    
    /// 登录标记
    var isLogin: Bool {
        return access_token != nil
    }
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// 当前授权用户的UID
    var uid: String?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet{
            
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    /// 过期日期
    var expiresDate: NSDate?
    
    // 构造方法 - 直接加private限制用户调用
    private override init() {
        super.init()
        loadUserAccount()
    }
    

    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        
        let keys = ["access_token", "uid", "expiresDate", "expires_in", "screen_name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }

}
// MARK : - 加载保存用户账户
extension UserAccount {
    
    func updateUserAccount(dict: [String: AnyObject]) {
        
        setValuesForKeysWithDictionary(dict)
        saveUserAccount()
    }
    
    //保存到用户偏好
    private func saveUserAccount() {
        
        //1.模型转字典
        let keys = ["access_token", "uid", "expiresDate", "screen_name", "avatar_large"]
        let dict = dictionaryWithValuesForKeys(keys)

        //2. 将字典写入偏好设置
        NSUserDefaults.standardUserDefaults().setObject(dict, forKey: LDWeiboUserAccountKey)
    }
    // 加载
    private func loadUserAccount() {
        
       guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(LDWeiboUserAccountKey) as? [String: AnyObject] else {
            
            return
        }
        //字典转模型
        setValuesForKeysWithDictionary(dict)
        
        if isExpried {
            access_token = nil
        }
    }
    private var isExpried: Bool {
        
        return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    
}










